package br.com.kauepbarreto.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaQuery;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;

import br.com.kauepbarreto.util.JPAUtil;

public class DAO<T> {
	
	private final Class<T> classe;
	
	public DAO(Class<T> classe){
		this.classe = classe;
	}
	
	public void insert(T t){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
		//abre transacao
		em.getTransaction().begin();

		//persiste o objeto
		em.persist(t);
		
		//commita  a transacao
		em.getTransaction().commit();
		//fecha a entity manager
		em.close();
	}
	
	public void delete(T t){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
		//abre transacao 
		em.getTransaction().begin();

		//persiste o objeto
		em.remove(em.merge(t));
		
		//commita  a transacao
		em.getTransaction().commit();
		//fecha a entity manager
		em.close();
	}
		
	
	public void update(T t){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
		//abre transacao 
		em.getTransaction().begin();

		//persiste o objeto
		em.merge(t);
		
		//commita  a transacao
		em.getTransaction().commit();
		//fecha a entity manager
		em.close();
	}

	public List<T> getAll(){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
		CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(classe);
		query.select(query.from(classe));
		
		List<T> lista = em.createQuery(query).getResultList();
		
		//fecha a entity manager
		em.close();
		
		return lista;
	}

	public List<T> getList(T t){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
			
		Session session = (Session) em.getDelegate();

		Criteria crit = session.createCriteria(classe)
		.add(Example.create(t));

		@SuppressWarnings("unchecked")
		List<T> Lista = (List<T>) crit.list();

		return Lista;		
		
	}	
	
	public T get(T t){
		//consegue a entity manager
		EntityManager em = new JPAUtil().getEntityManager();
			
		Session session = (Session) em.getDelegate();

		Criteria crit = session.createCriteria(classe)
		.add(Example.create(t));

		@SuppressWarnings("unchecked")
		T entity = (T)crit.uniqueResult();

		return entity;		
		
	}
	
	public T getById(Long Id){

		EntityManager em = new JPAUtil().getEntityManager();
		return (T) em.find(classe, Id);
		
	}	
}
